/*
 * @Author: your name
 * @Date: 2020-12-30 19:52:28
 * @LastEditTime: 2021-01-03 23:50:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \H5 2010 studyd:\H5 2010 练习\第三阶段 Vue + node\DAY 7\panda\src\store\modules\user.js
 */
import { login } from '@/api/user'

// 从本地缓存中读取用户基本信息及 token
const userInfo = JSON.parse(localStorage.getItem('userInfo')) || JSON.parse(sessionStorage.getItem('userInfo')) || {}
const token = localStorage.getItem('token') || sessionStorage.getItem('token') || ''

export default {
  namespaced: true,
  state: {
    userInfo,
    token // 相当于令牌
  },
  mutations: {
    // 登陆成功
    loginSuccess(state, { userInfo, token }) {
      state.userInfo = userInfo
      state.token = token
    },
    // 退出成功
    logoutSuccess(state) {
      state.userInfo = {}
      state.token = ''
    }
  },
  actions: {
    // 实现异步登录，更新状态数据
    loginAsync(store, { username, password, remember }) {
      // 异步登录
      return login(username, password)
        .then(res => {
          // 提交 mutation 来实现状态更新
          store.commit('loginSuccess', { ...res, remember })
          return {
            success: true
          }
        })
        .catch(err => {
          console.log('登录异常：', err.message)
        })
    }
  }
}
